package com.learn.demo.listener;

import com.learn.demo.webserver.ClusterWebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

/**
 * 集群聊天消息监听器
 *
 * @author banjiawei
 * @date 2021/05/11
 */
@Component
@Slf4j
public class ChatMessageListener implements MessageListener {
    @Autowired
    @Qualifier("redisTemplate15")
    private RedisTemplate<String, Object> redisTemplate15;
    @Autowired
    private ClusterWebSocketServer webSocketServer;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<String> valueSerializer = redisTemplate15.getStringSerializer();
        String messageStr = valueSerializer.deserialize(message.getBody());
        if (StringUtils.isNotBlank(messageStr)) {
            //推送消息
            webSocketServer.sendClusterWebSocketMessage(messageStr);
        }
    }
}
